import {
    Typography,
    Input,
    Button,
    Space,
    Card,
    Collapse, Row, message
} from "antd";
import BriefIntroduction from "../BriefIntroduction/BriefIntroduction";

import {useEffect, useRef, useState} from "react";
import {UndoOutlined} from "@ant-design/icons";
import {addBookContentAPI, getChapterContentAPI, saveChapterContentAPI} from "../../../../apis/novel.js";
import {useLocation} from "react-router-dom";

const {Paragraph} = Typography;
const {TextArea} = Input


// 每一章的内容
const Content = () => {

    const location = useLocation()
// 内容排列方向
    const [contentDirection, setContentDirection] = useState('horizontal')


    // 生成内容
    const [content, setContent] = useState('')

    // 生成内容方法
    const generateContent = async (index) => {
        let data = {
            events: JSON.parse(window.localStorage.getItem('events')),
            index,
            headline: window.localStorage.getItem('headline'),
            detail: '',
            model: window.localStorage.getItem('gpt')
        }

        let res = await addBookContentAPI(data)
        console.log('生成内容', res)

        setContent(content + '\n' + res.data.detail)
    }


    // 保存的内容
    const [savedContentData, setSavedContentData] = useState('')


    // 获取章节内容
    const getContentData = () => {

        getChapterContentAPI(location.state.novelInfo.bookId).then(res => {
            console.log('获取章节内容', res.data.content)

            if (res.code == '0000') {
                setSavedContentData(res.data.content)
                message.success('获取成功')
            } else {
                message.error('获取失败')
            }
        })
    }

    useEffect(() => {
        getContentData()
    }, []);

    //保存内容
    const saveContentData = async () => {
        let data = {
            chapterId: window.localStorage.getItem('chapterId'),
            bookId: location.state.novelInfo.bookId,
            content: content,
            headline: window.localStorage.getItem('headline'),
            topic: '',
            illustration: ''
        }

        let res = await saveChapterContentAPI(data)

        if (res.code === '0000') {
            message.success('保存成功')
        } else {
            message.error('保存失败')
        }

        getContentData()
    }


    // 生成txt文件保存本地
    const saveText = () => {
// 要保存的字符串
        const stringData = savedContentData
        // dada 表示要转换的字符串数据，type 表示要转换的数据格式
        const blob = new Blob([stringData], {
            type: "text/plain;charset=utf-8"
        })
        // 根据 blob生成 url链接
        const objectURL = URL.createObjectURL(blob)

        // 创建一个 a 标签Tag
        const aTag = document.createElement('a')
        // 设置文件的下载地址
        aTag.href = objectURL
        // 设置保存后的文件名称
        aTag.download = 'FusionMind' + new Date().getFullYear().toString() + new Date().getMonth().toString() + new Date().getDay().toString() + new Date().getTime().toString() + ".txt"
        // 给 a 标签添加点击事件
        aTag.click()
        // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
        // 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
        URL.revokeObjectURL(objectURL)
    }


    const items = [
        {
            key: '1',
            label: '章节情节',
            children: <BriefIntroduction setContent={setContent} content={content}/>,
        },
        {
            key: '2',
            label: <Space>
                <span>章节内容生成</span>
            </Space>,
            children: <>
                <Row justify={'end'}>
                    <Button type={"primary"} onClick={(e) => {
                        setContentDirection(contentDirection === 'vertical' ? 'horizontal' : 'vertical')
                    }}>
                        <UndoOutlined/>
                    </Button>
                </Row>
                <Space style={{
                    width: '100%',
                }} direction={contentDirection}>
                    {savedContentData &&  savedContentData.length > 0 && <Card title={'章节内容(已保存)'}>
                        <Typography>
                            <Paragraph>
                        <pre style={{
                            textAlign: 'left'
                        }}>{savedContentData}</pre>
                            </Paragraph>
                        </Typography>
                    </Card>}
                    <Card
                        title='内容生成'
                        style={{
                            width: 500,
                            minWidth: '100%'
                        }}
                        extra={
                            <Space size={'middle'}>
                                <Button type='primary' onClick={saveContentData}>保存</Button>
                                <Button type='primary' onClick={saveText}>下载到本地</Button>
                            </Space>
                        }
                    >
                        <TextArea
                            onChange={(e) => {
                                setContent(e.target.value)
                            }}
                            autoSize={{
                                minRows: 7,
                                maxRows: 99,
                            }} value={content}/>
                    </Card>
                </Space>
            </>

        },
    ];


    return (
        <>

            <Collapse items={items} defaultActiveKey={['1', '2']}/>

        </>
    )
}

export default Content